import {
  getStandProductByPage,
  addStandProduct,
  updateStandProduct,
  delStandProduct,
  exportStandProduct,
  getProductTypeList,
  getStandFileType,
  getBopCodeAndName,
  downloadFile,
  getFileByFileCode,
  getDrawingTypeList,
  uploadStandFileInfoDrawing,
  uploadStandFileInfoBom,
  bom_downloadFile,
  getStandProductByStandTypeName,
  submitStandProduct,
  approveStandProduct,
  exportStandProductProcessInfoByStandTypeIds,
  uploadStandProductProcessInfo,
} from '@/services/design/standProduct';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { downloadStandardBom } from '@/services/design/productBomOverview';
import {
  PlusOutlined,
  UploadOutlined,
  DownloadOutlined,
  AlignCenterOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Select,
  Upload,
  InputNumber,
  Tabs,
  Row,
  Col,
  TabsProps,
  notification,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { Ellipsis } from '@/components/Ellipsis';
import { history, useModel } from 'umi';
import StandProductProcessInfo from './standProductProcessInfo';
import StandFileInfoBOM from './standFileInfoBOM';
import StandFileInfodrawing from './standFileInfodrawing';
import './style.less';
import StandProductBomDesign from './standProductBomDesign';
import { getMaterialInfoByMaterialProperty } from '@/services/baseData/materialInfo';

const StandProduct: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const [modalVisit2, setModalVisit2] = useState(false); // 上传附件页面用到
  const [confirmLoading2, setConfirmLoading2] = useState(false);

  const [modalVisit3, setModalVisit3] = useState(false); // 上传附件页面用到
  const [confirmLoading3, setConfirmLoading3] = useState(false);

  const [modalVisit4, setModalVisit4] = useState(false); // 新建和编辑提示框
  const [confirmLoading4, setConfirmLoading4] = useState(false);

  const [modalVisit5, setModalVisit5] = useState(false); // 上传工时周期页面用到
  const [confirmLoading5, setConfirmLoading5] = useState(false);

  const [optionsTypeDesc, setoptionsTypeDesc] = useState([]); //下拉框用到
  const [optionsstandfile, setoptionsstandfile] = useState([]);
  const [optionsbopCode, setoptionsbopCode] = useState([]);
  const [optionsMaterialCode, setOptionsMaterialCode] = useState([]);
  const [materialCodeToName, setMaterialCodeToName] = useState([]); //用来保存物料主数据的物料编号、物料id和物料名称

  const [filefilename, setfilefilename] = useState([]); //保存要下载的文件名称
  const [open, setOpen] = useState(false); //控制查看Modal的开关

  const [thecode, setthecode] = useState(''); //柜体编号
  const [thedes, setthedes] = useState(''); //柜体类型
  const [theid, settheid] = useState(''); //柜体类型
  const [thename, setthename] = useState(''); //柜体名称
  const [thestate, setthestate] = useState(''); //柜体审批状态
  const [activeKey, setActiveKey] = useState('1'); //tab页面默认激活索引
  const [loading, setLoading] = useState(false);
  const [selectionsWorkHours, setSelectionsWorkHours] = useState([]);

  const [file, setFile] = useState([]);
  const [file2, setFile2] = useState();
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const [productType, setProductType] = useState();
  const [productTotalInfo, setProductTotalInfo] = useState([]);
  const [isFormRepeat, setIsFormRepeat] = useState(false); //判断描述字段是否重复
  const [formResultStandTypeName, setFormResultStandTypeName] = useState('');
  const ref = useRef(null);
  const { TextArea } = Input;
  const { initialState } = useModel('@@initialState'); //hooks获取全局的共享的当前用户信息
  const [userRight, setUserRight] = useState(false); //当前用户是否有页面部分关键功能的权利，比如说柜体审核
  const [userRole, setUserRole] = useState<string[]>(); //当前用户的身份
  //类型定义
  type tabType = {
    name: string;
    label: string;
    content: JSX.Element;
  };
  useEffect(() => {
    try {
      if (!initialState?.currentUser) {
        history.replace('/user/login');
        notification.error({
          message: '获取用户信息失败',
          description: '获取用户信息失败，将跳回到登录页面',
        });
        throw new Error('获取用户信息失败');
      }
      console.log('initialState', initialState);
      setUserRole(initialState.roleInfo);
      if (
        initialState.roleInfo.includes('ROLE_Admin') ||
        initialState.roleInfo.includes('ROLE_TechManager')
      ) {
        setUserRight(true);
      }
      getMaterialCodeOptions();
    } catch (err) {
      console.log(err);
    }
  }, []);

  const permissionSet = (record: any): boolean => {
    let res = true;
    // console.log(record, 'record');
    // console.log(userRole, 'userRole');
    //在新建柜体页面
    if (record.state === 0) {
      //如果是管理员或者是技术工程师
      if (userRole?.includes('ROLE_Admin') || userRole?.includes('ROLE_TechOperator')) res = false;
    }
    //在待审批页面
    else if (record.state === 1) {
      //如果是管理员或者是技术经理
      if (userRole?.includes('ROLE_Admin') || userRole?.includes('ROLE_TechManager')) res = false;
    }
    return res;
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      search: false,
      align: 'center',
      sorter: true,
      width: 60,
    },
    {
      title: '柜体类型',
      valueType: 'select',
      dataIndex: 'standTypeDesc',
      align: 'center',
      sorter: true,

      fieldProps: {
        options: optionsTypeDesc,
      },
      // renderFormItem: () => {
      //   return (
      //     <Select
      //       placeholder="请选择标准柜体类型"
      //       // onChange={(value, label) => {}}
      //       options={optionsTypeDesc}
      //       // value={standTypeDesc}
      //       allowClear={true}
      //     />
      //   );
      // },
      width: 80,
    },
    {
      title: '柜体编号',
      dataIndex: 'standTypeCode',
      align: 'center',
      sorter: true,

      width: 120,
    },
    // {
    //   title: '工艺路径',
    //   dataIndex: 'bopCode',
    // },
    {
      title: '柜体名称',
      dataIndex: 'standTypeName',
      align: 'center',
      sorter: true,
      width: 160,
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      align: 'center',
      sorter: true,
      width: 120,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      align: 'center',
      sorter: true,
      width: 120,
    },
    // {
    //   title: '计划设计工时(h)',
    //   search: false,
    //   dataIndex: 'standDesignWorkHour',
    //  align: 'center',sorter: true,
    //   render: (text, record, _, action) => {
    //     return <div>{record.standDesignWorkHour}</div>;
    //   },
    //   width: 80,
    // },
    {
      title: '计划生产工时(h)',
      search: false,
      dataIndex: 'standManufactWorkHour',
      align: 'center',
      sorter: true,
      render: (text, record, _, action) => {
        return <div>{record.standManufactWorkHour}</div>;
      },
      width: 160,
    },
    {
      title: 'BOM标识',
      search: false,
      dataIndex: 'isBomUpload',
      align: 'center',
      sorter: true,

      render: (text) => {
        return <div>{text == 1 ? '已上传' : '未上传'}</div>;
      },
      width: 80,
    },
    {
      title: '图纸标识',
      search: false,
      dataIndex: 'isDrawingUpload',
      align: 'center',
      sorter: true,

      render: (text) => {
        return <div>{text == 1 ? '已上传' : '未上传'}</div>;
      },
      width: 80,
    },
    {
      title: '状态',
      // valueEnum:{{label:'待提交',value:0}}
      align: 'center',
      sorter: true,
      dataIndex: 'state',
      width: 60,
      render: (text) => <div>{text == 0 ? '待提交' : text == 1 ? '待审核' : '已审核'}</div>,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      align: 'center',
      sorter: true,
      width: 80,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,

      width: 80,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setProductTotalInfo(record);
            console.log('保存记录', productTotalInfo);
            setthecode(record.standTypeCode);
            setthedes(record.standTypeDesc);
            settheid(record.id);
            setthename(record.standTypeName);
            setOpen(true);
            setCreateOrUpdate(true);
            setthestate(record.state);
            form.setFieldsValue({
              memo: record.memo,
              bomMultipartFile: record.bomMultipartFile,
              standDesignWorkHour: record.standDesignWorkHour,
              drawingMultipartFile: record.drawingMultipartFile,
              standManufactWorkHour: record.standManufactWorkHour,
              standTypeCode: record.standTypeCode,
              standTypeDesc: record.standTypeDesc,
              bopCode: record.bopCode,
              id: record.id,
              standTypeName: record.standTypeName,
              materialCode: record.materialCode,
              materialInfoId: record.materialCode,
              materialName: record.materialName,
            });
            // console.log(record.id);
            setFormResultStandTypeName(record.standTypeName);
          }}
        >
          详情
        </a>,
        <a
          key="fileInfo"
          hidden={record.state === 1 || record.state === 2}
          onClick={() => {
            history.push({
              pathname: '/design/standProductFileInfo',
              state: {
                record: record,
              },
            });
          }}
        >
          设计
        </a>,
        // <a
        //   key="uploadBOM"
        //   hidden={record.state === 1 || record.state === 2}
        //   onClick={() => {
        // setModalVisit2(true);
        //     form.setFieldsValue({
        //       standTypeCode: record.standTypeCode,
        //       standTypeDesc: record.standTypeDesc,
        //       memo: record.memo,
        //       id: record.id,
        //       standTypeName: record.standTypeName,
        //       category: 'BOM',
        //     });
        //   }}
        // >
        //   BOM上传
        // </a>,
        // <a
        //   key="uploadDrawing"
        //   hidden={record.state === 1 || record.state === 2}
        //   onClick={() => {
        //     setModalVisit3(true);
        //     form.setFieldsValue({
        //       standTypeCode: record.standTypeCode,
        //       standTypeDesc: record.standTypeDesc,
        //       memo: record.memo,
        //       id: record.id,
        //       standTypeName: record.standTypeName,
        //       category: '',
        //     });
        //   }}
        // >
        //   图纸上传
        // </a>,
        <a
          key="submitProduct"
          hidden={permissionSet(record)}
          onClick={async () => {
            if (record.state === 0) {
              const result = await submitStandProduct(record);
              // console.log('提交标准柜体结果:', result.data);
              if (result.data.length === 0) {
                message.success('标准柜体提交成功！');
                actionRef.current?.reload();
              } else {
                // result.data.forEach((item: any) => {
                //   notification.error({
                //     message: '提交失败',
                //     description: item,
                //     duration: 2,
                //   });
                // });
                notification.error({
                  message: '提交失败',
                  description: result.data,
                  duration: 2,
                });
                actionRef.current?.reload();
              }
            } else if (record.state === 1) {
              setModalVisit4(true);
              form1.setFieldsValue({
                standTypeId: record.id,
              });
            }
          }}
        >
          {record.state === 0 ? '提交' : '审批'}
        </a>,
        <a
          key="deleteKey"
          hidden={record.state === 1}
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delStandProduct({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  // 选择标准柜体,导出工时模板
  const rowSelectionWorkHours = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp: string[] = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push(item.id);
        });
      }
      console.log(temp, 'temp');
      setSelectionsWorkHours(temp); //选中的柜体
    },
  };

  // 上传工时模板提交
  const workhour_upload = async () => {
    setConfirmLoading5(true);
    form
      .validateFields()
      .then(async () => {
        const res = { ...form.getFieldsValue() };
        const formData = new window.FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        const result = await uploadStandProductProcessInfo({ file: res.file });
        if (result != null && result.code == 0) {
          message.success('上传成功');
          form.resetFields();
        }
        setConfirmLoading5(false);
        setModalVisit5(false);
        actionRef.current!.reload();
      })
      .catch(() => {
        setConfirmLoading5(false);
      });
  };

  const standStateTable: TabsProps['items'] = [
    {
      key: '1',
      label: '待提交',
      children: (
        <>
          <ProTable
            className="ProTable"
            headerTitle="标准柜体查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={tableSearchPublicConfig}
            toolBarRender={(action, { selectedRows }) => [
              <Button
                key="workhour_button"
                type="primary"
                onClick={async () => {
                  if (selectionsWorkHours.length == 0) {
                    message.info('请选择标准柜');
                  } else {
                    console.log(selectionsWorkHours);
                    exportStandProductProcessInfoByStandTypeIds(selectionsWorkHours).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = URL.createObjectURL(res);
                      const filenmae = '工时模板.xls';
                      aLink.setAttribute('download', filenmae);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }
                }}
              >
                工时模板下载
              </Button>,
              <Button
                key="workhour_upload_button"
                type="primary"
                onClick={() => {
                  setModalVisit5(true);
                  form.setFieldsValue({
                    file: '',
                  });
                }}
              >
                工时上传
              </Button>,
              <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCreateOrUpdate(false);
                  setFormTitle('新建');
                  form.resetFields();
                  setModalVisit(true);
                }}
                type="primary"
              >
                新建
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const filterNew = { ...params, state: 0 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(filterNew);
              const result = await getStandProductByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              //日期处理，只保留日期的年月日部分
              result.data.content.map((item: any) => {
                item.createTime = item.createTime.split(' ')[0];
                item.standDesignWorkHour = item.standDesignWorkHour.toFixed(2);
                item.standManufactWorkHour = item.standManufactWorkHour.toFixed(2);
              });
              // console.log('1111', result);
              getproductInfo();
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1700, y: 600 }}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            // scroll={{ x: 1700, y: 'calc(100vh - 460px)' }}
            rowSelection={{
              selectionsWorkHours,
              ...rowSelectionWorkHours,
            }}
          />
        </>
      ),
    },
    {
      key: '2',
      label: '待审批',
      children: (
        <>
          <ProTable
            className="ProTable"
            headerTitle="标准柜体查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={tableSearchPublicConfig}
            toolBarRender={(action, { selectedRows }) => [
              // <Button
              //   key="button"
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     setCreateOrUpdate(false);
              //     setFormTitle('新建');
              //     form.resetFields();
              //     setModalVisit(true);
              //   }}
              //   type="primary"
              // >
              //   新建
              // </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const filterNew = { ...params, state: 1 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(filterNew);

              const result = await getStandProductByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              //日期处理，只保留日期的年月日部分
              result.data.content.map((item: any) => {
                item.createTime = item.createTime.split(' ')[0];
                item.standDesignWorkHour = item.standDesignWorkHour.toFixed(2);
                item.standManufactWorkHour = item.standManufactWorkHour.toFixed(2);
              });
              console.log('1111', result);
              getproductInfo();
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            // scroll={{ x: 1700, y: 400 }}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            scroll={{ x: 1700, y: 450 }}
            rowSelection={{}}
          />
        </>
      ),
    },
    {
      key: '3',
      label: '已审批',
      children: (
        <>
          <ProTable
            className="ProTable"
            headerTitle="标准柜体查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            search={tableSearchPublicConfig}
            toolBarRender={(action, { selectedRows }) => [
              // <Button
              //   key="button"
              //   icon={<PlusOutlined />}
              //   onClick={() => {
              //     setCreateOrUpdate(false);
              //     setFormTitle('新建');
              //     form.resetFields();
              //     setModalVisit(true);
              //   }}
              //   type="primary"
              // >
              //   新建
              // </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const filterNew = { ...params, state: 2 };
              const sorters = sortTran(sort);
              const filters = filterTranNew(filterNew);

              const result = await getStandProductByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              //日期处理，只保留日期的年月日部分
              result.data.content.map((item: any) => {
                item.createTime = item.createTime.split(' ')[0];
                item.standDesignWorkHour = item.standDesignWorkHour.toFixed(2);
                item.standManufactWorkHour = item.standManufactWorkHour.toFixed(2);
              });
              console.log('标准柜体数据:', result);

              getproductInfo();
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 1700, y: 450 }}
            pagination={{
              defaultPageSize: 100,
              defaultCurrent: 1,
              pageSizeOptions: [100, 500, 1000],
              showSizeChanger: true,
            }}
            // scroll={{ x: 1700, y: 'calc(100vh - 460px)' }}
            rowSelection={{}}
          />
        </>
      ),
    },
  ];
  //定义Tabs的子结构的数组
  const tabList: tabType[] = [
    {
      name: 'tab1',
      label: '柜体编辑',
      content: (
        <div>
          <Form
            name="wrap"
            labelCol={{ flex: '110px' }}
            labelAlign="right"
            labelWrap
            form={form}
            wrapperCol={{ flex: 1 }}
            colon={false}
            style={{ margin: 40 }}
          >
            <Form.Item label="id" name="id" hidden={true}>
              <Input />
            </Form.Item>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="标准柜体类型"
                  name="standTypeDesc"
                  rules={[{ required: true, message: '请选择标准柜体类型!' }]}
                >
                  <Select
                    placeholder="请选择标准柜体类型"
                    disabled={createOrUpdate} //不可更改
                    onChange={(value, label) => {}}
                    options={optionsTypeDesc}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="标准柜体编号"
                  name="standTypeCode"
                  rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
                  hidden={!createOrUpdate}
                >
                  <Input disabled />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="标准柜体名称"
                  name="standTypeName"
                  rules={[
                    {
                      required: true,
                      validator: (rule, value, callback) => {
                        valueChangeValidCheck(value, callback);
                      },
                    },
                  ]}
                >
                  <Input maxLength={20} showCount disabled={thestate !== 0} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="工艺路径"
                  name="bopCode"
                  rules={[{ required: true, message: '请选择工艺路径!' }]}
                >
                  <Select
                    disabled={createOrUpdate}
                    placeholder="请选择工艺路径"
                    // disabled={createOrUpdate}//不可更改
                    onChange={(value) => {}}
                    options={optionsbopCode}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="计划设计工时"
                  name="standDesignWorkHour"
                  // rules={[{ required: false, message: '请输入计划设计工时!' }]}
                >
                  <Input
                    addonAfter="h"
                    onChange={(e) => handlestandDesignWorkHourChange(e.target.value)}
                    disabled={thestate !== 0}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label="计划生产工时"
                  name="standManufactWorkHour"
                  // rules={[{ required: true, message: '请输入计划生产工时!' }]}
                >
                  <Input
                    addonAfter="h"
                    onChange={(e) => handlestandManufactWorkHourChange(e.target.value)}
                    disabled={true}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item label="物料id" name="materialInfoId" hidden={true}>
              <Input disabled />
            </Form.Item>
            <Row gutter={[50, 0]}>
              <Col span={12}>
                <Form.Item
                  label="物料编号"
                  name="materialCode"
                  rules={[{ required: true, message: '请选择物料编号 !' }]}
                >
                  <Select
                    disabled={thestate !== 0}
                    showSearch
                    placeholder="请选择物料编号"
                    filterOption={filterOption}
                    options={optionsMaterialCode}
                    onChange={(value) => {
                      console.log(materialCodeToName, 'materialCodeName');
                      let data = materialCodeToName.find(
                        (item: any) => item.materialCode === value,
                      );
                      form.setFieldsValue({
                        materialName: data?.materialName,
                        materialInfoId: data?.materialInfoId,
                      });
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="物料名称" name="materialName">
                  <Input disabled />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item label="备注" name="memo">
              <TextArea autoSize={{ minRows: 2, maxRows: 6 }} disabled={thestate !== 0} />
            </Form.Item>
          </Form>
          <div style={{ width: 1100, textAlign: 'center' }}>
            <Button
              type="primary"
              onClick={() => {
                editSubmit();
              }}
            >
              确定
            </Button>
          </div>
        </div>
      ),
    },
    {
      name: 'tab2',
      label: '工时周期',
      content: (
        <div>
          <StandProductProcessInfo thestandid={theid} thestate={thestate} />
        </div>
      ),
    },
    {
      name: 'tab3',
      label: '图纸列表',
      content: (
        <div>
          <StandFileInfodrawing
            thestandTypeCode={thecode}
            thestandTypeDesc={thedes}
            thestandid={theid}
            thestandname={thename}
            thestate={thestate}
          />
        </div>
      ),
    },
    {
      name: 'tab4',
      label: 'BOM列表',
      content: (
        <div>
          <StandFileInfoBOM
            thestandTypeCode={thecode}
            thestandTypeDesc={thedes}
            thestandid={theid}
            thestandname={thename}
            thestate={thestate}
          />
        </div>
      ),
    },

    {
      name: 'tab5',
      label: 'BOM清单',
      // children: <StandProductBomDesign standTypeId={theid}></StandProductBomDesign>,
      content: (
        <div>
          <StandProductBomDesign standTypeId={theid}></StandProductBomDesign>
        </div>
      ),
    },
  ];

  // 新建标准柜
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const res = form.getFieldsValue();
      res.standManufactWorkHour = 0;
      res.standDesignWorkHour = parseFloat(res.standDesignWorkHour).toFixed(2);
      res.standManufactWorkHour = parseFloat(res.standManufactWorkHour).toFixed(2);
      console.log(res, '保留两位小数');
      if (isFormRepeat) {
        message.error('标准柜体名称重复！');
        setConfirmLoading(false);
        actionRef.current!.reload();
        return false;
      }
      if (
        res.standTypeDesc == undefined ||
        res.bopCode == undefined ||
        res.standDesignWorkHour == undefined ||
        res.standManufactWorkHour == undefined ||
        res.standTypeName == undefined
      ) {
        message.error('必填项为空！');
        setConfirmLoading(false);
        actionRef.current!.reload();
        return false;
      }
      console.log(res, '新建的项');
      const result = await addStandProduct(res);
      console.log(result);
      if (result != null) {
        message.success('添加成功，请配置工时工序！');
        setthecode(result.data.standTypeCode);
        setthedes(result.data.standTypeDesc);
        settheid(result.data.id);
        setthename(result.data.standTypeName);
        setProductTotalInfo(result.data);
        setCreateOrUpdate(true);
        setthestate(0);
        setOpen(true); //新建完标准柜体跳转至设置工序工时界面
        setActiveKey('2'); //将默认tab页改为tab2工序工时页面
      }
      setConfirmLoading(false);
      setModalVisit(false);
      actionRef.current!.reload();
    }
  };

  const handleSubmit2 = async () => {
    setConfirmLoading4(true);
    form1
      .validateFields()
      .then(async () => {
        const res = form1.getFieldsValue();
        const result = await approveStandProduct(res);
        console.log('提交标准柜体结果:', result.message);
        if (result.message) {
          message.success('标准柜体审核成功！');
          setModalVisit4(false);
          setConfirmLoading4(false);
          actionRef.current?.reload();
        } else {
          notification.error({
            message: '审核失败',
          });
          setModalVisit4(false);
          setConfirmLoading4(false);
          actionRef.current?.reload();
        }
      })
      .catch(() => {
        setConfirmLoading4(false);
        actionRef.current?.reload();
        message.error('审核有选项未填写！');
      });
  };

  // 编辑提交按钮
  const editSubmit = async () => {
    setConfirmLoading(true);
    const res = form.getFieldsValue();
    res.standTypeId = res.id;
    res.standDesignWorkHour = parseFloat(res.standDesignWorkHour).toFixed(2);
    res.standManufactWorkHour = parseFloat(res.standManufactWorkHour).toFixed(2);
    console.log('编辑提交信息：', res);
    if (isFormRepeat) {
      message.error('标准柜体名称重复！');
      setConfirmLoading(false);
      actionRef.current!.reload();
      return false;
    }
    if (
      res.standTypeDesc == undefined ||
      res.bopCode == undefined ||
      res.standDesignWorkHour == undefined ||
      res.standManufactWorkHour == undefined ||
      res.standTypeName == ''
    ) {
      message.error('必填项为空！');
      setConfirmLoading(false);
      actionRef.current!.reload();
      return false;
    }
    const result = await updateStandProduct(res);
    console.log('编辑提交反馈结果：', result);
    if (result != null) {
      message.success('修改成功');
    }
    setConfirmLoading(false);
    setOpen(false);
    actionRef.current!.reload();
  };

  // 上传BOM
  const handleBOM = async () => {
    setConfirmLoading2(true);
    form
      .validateFields()
      .then(async (value) => {
        const res = form.getFieldsValue();
        const formData = new window.FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        res.standTypeId = res.id;
        res.category = 'BOM';
        console.log(res);
        const result = await uploadStandFileInfoBom(res);
        if (result != null) {
          message.success('上传成功');
        }
        setConfirmLoading2(false);
        setModalVisit2(false);
        actionRef.current!.reload();
      })
      .catch((err) => {
        setConfirmLoading2(false);
        console.log(err);
      });
  };

  // 上传图纸
  const handledrawing = async () => {
    setConfirmLoading3(true);
    form
      .validateFields()
      .then(async (value) => {
        const res = form.getFieldsValue();
        const formData = new window.FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        res.standTypeId = res.id;
        console.log(res);
        const result = await uploadStandFileInfoDrawing(res);
        if (result != null) {
          message.success('上传成功');
        }
        setConfirmLoading3(false);
        setModalVisit3(false);
        actionRef.current!.reload();
      })
      .catch((err) => {
        setConfirmLoading3(false);
        console.log(err);
      });
  };

  const onFilesChange = (file: any) => {
    setFile(file.fileList);
  };

  const beforeUpload = (file) => {
    console.log(file);
    setFile(file);
    return false;
  };

  // 限制图纸大小
  const handleBeforeUpload = (info: any) => {
    //检验文件大小
    // info.size文件大小单位是字节
    // const isLt = info.size / 1024 / 1024 < 5;
    // if (!isLt) {
    //   alert(`上传文件大小不能超过 ${5} MB!`);
    // }
    // return isLt || Upload.LIST_IGNORE;
    return false;
  };

  //取消查看Modal的弹窗
  const handleCancel = () => {
    setOpen(false);
    setActiveKey('1'); //将默认tab页改为tab2工序工时页面
    actionRef.current!.reload(); //关闭实现页面刷新
  };

  //获取标准柜体类型和文件类别
  const getproductInfo = async () => {
    // 获取柜体类型
    const getproduct = await getProductTypeList(null);
    const productOptionContract: any[] = [];
    getproduct.data.map((item: any, index: any) => {
      productOptionContract.push({ label: item, value: item });
    });
    // console.log('111', getproduct);

    setoptionsTypeDesc(productOptionContract);
    // 获取图纸类型
    const gettype = await getDrawingTypeList(null);
    const productfiletype: any[] = [];
    gettype.data.map((item: any, index: any) => {
      productfiletype.push({ value: item, label: item });
    });
    setoptionsstandfile(productfiletype);
    // 获取工艺路径编号和名称
    const getcode = await getBopCodeAndName(null);
    const codeandname = [];
    getcode.data.map((item: any, index: any) => {
      codeandname.push({ value: item.bopCode, label: item.bopName });
    });
    // console.log(codeandname);
    setoptionsbopCode(codeandname);
  };

  //通过文件编号获取文件名
  const getfilenamebycode = async (code) => {
    const getname = await getFileByFileCode(code);
    setfilefilename(getname.data.fileName);
  };

  const handlestandDesignWorkHourChange = (value: any) => {
    if (value && !isNaN(value)) {
      const formattedValue = value
        .replace(/[^\d.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
        .replace(/^\./g, '');
      console.log(formattedValue);
      form.setFieldsValue({ standDesignWorkHour: formattedValue });
    }
  };

  const handlestandManufactWorkHourChange = (value: any) => {
    if (value && !isNaN(value)) {
      const formattedValue = value
        .replace(/[^\d.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
        .replace(/^\./g, '');
      console.log(formattedValue);
      form.setFieldsValue({ standManufactWorkHour: formattedValue });
    }
  };
  const changeTabs = async (key: string) => {
    console.log('tab页索引：', key);
    if (key === '1') {
      const result = await getStandProductByPage({
        current: 1,
        filters: [],
        pageSize: 100,
        sorters: [],
      });
      console.log('111', result);
      result.data.content.map((item: any) => {
        if (item.id === productTotalInfo.id) {
          item.createTime = item.createTime.split(' ')[0];
          item.standDesignWorkHour = item.standDesignWorkHour.toFixed(2);
          item.standManufactWorkHour = item.standManufactWorkHour.toFixed(2);
          setProductTotalInfo(item);
          console.log('这是更新后的数据', productTotalInfo);
          form.setFieldsValue({
            memo: item.memo,
            bomMultipartFile: item.bomMultipartFile,
            standDesignWorkHour: item.standDesignWorkHour,
            drawingMultipartFile: item.drawingMultipartFile,
            standManufactWorkHour: item.standManufactWorkHour,
            standTypeCode: item.standTypeCode,
            standTypeDesc: item.standTypeDesc,
            bopCode: item.bopCode,
            id: item.id,
            standTypeName: item.standTypeName,
          });
        }
      });
    }
  };
  //判断是否字段重复
  const valueChangeValidCheck = async (value: String, callback: any) => {
    setIsFormRepeat(false);
    console.log('标准柜体描述：', value);
    const result = await getStandProductByStandTypeName(value);
    console.log('查询结果是否重复：', result.data);
    console.log(formResultStandTypeName);
    if (result.data !== null && value !== formResultStandTypeName) {
      setIsFormRepeat(true);
      callback('标准柜体名称已存在');
    }
  };

  //获取物料编号的下拉框内容
  const getMaterialCodeOptions = async () => {
    const result = await getMaterialInfoByMaterialProperty('产成品');
    console.log(result, '产成品');
    /*     const result = await getMaterialInfoByPage({
          current: 1,
          filters: [{
            andOr: 'and',
            field: 'materialProperty',
            operator: 'like',
            value: '产成品'
          }],
          pageSize: 1000,
          sorters: [],
        }); */
    /*     let tempOptions: { value: string; label: string; }[] = [];
        let tempCodeToName: { materialCode: string; materialName: string }[] = [];
        result.data.content.map((item: any) => {
          tempOptions.push({ value: item.materialCode, label: item.materialCode });
          tempCodeToName.push({ materialCode: item.materialCode, materialName: item.materialName });
        })
        setMaterialCodeToName(tempCodeToName);
        setOptionsMaterialCode(tempOptions); */
    let tempOptions: { value: string; label: string }[] = [];
    let tempCodeToName: { materialInfoId: string; materialCode: string; materialName: string }[] =
      [];
    result.data.map((item: any) => {
      tempOptions.push({ value: item.materialCode, label: item.materialCode });
      tempCodeToName.push({
        materialInfoId: item.id,
        materialCode: item.materialCode,
        materialName: item.materialName,
      });
    });
    setMaterialCodeToName(tempCodeToName);
    setOptionsMaterialCode(tempOptions);
  };

  //下拉框搜索匹配
  const filterOption = (input: string, option: { label: string; value: string }) =>
    (option?.label ?? '').toLowerCase().includes(input.toLowerCase());

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        defaultActiveKey="1"
        destroyInactiveTabPane={true}
        animated={true}
        type="card"
        items={standStateTable}
        onChange={(e) => {
          console.log(e);
        }}
      />
      <Modal
        title="BOM上传"
        visible={modalVisit2}
        onOk={handleBOM}
        confirmLoading={confirmLoading2}
        onCancel={() => setModalVisit2(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '120px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="标准柜体类型"
            name="standTypeDesc"
            rules={[{ required: true, message: '请选择标柜体类型!' }]}
          >
            <Select
              placeholder="请选择标准柜体类型"
              disabled //不可更改
              onChange={(value, label) => {}}
              options={optionsTypeDesc}
            />
          </Form.Item>
          <Form.Item
            label="标准柜体编号"
            name="standTypeCode"
            rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="标准柜体名称"
            name="standTypeName"
            rules={[{ required: true, message: '请输入标准柜体名称!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Row justify={'space-between'}>
            <Col span={14}>
              <Form.Item
                label="文件类别"
                name="category"
                rules={[{ required: true, message: '请选择文件类别!' }]}
              >
                <Select
                  placeholder="请选择文件类别"
                  defaultValue=""
                  onChange={() => {}}
                  options={[{ value: 'BOM', label: 'BOM' }]}
                />
              </Form.Item>
            </Col>
            <Col>
              <Form.Item>
                <Button
                  key="bombutton"
                  icon={<DownloadOutlined />}
                  onClick={() => {
                    downloadStandardBom(null).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      aLink.setAttribute('download', `BOM导入模板.xls`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  下载BOM模板
                </Button>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            <Upload
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
              multiple={true}
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="图纸上传"
        visible={modalVisit3}
        onOk={handledrawing}
        confirmLoading={confirmLoading3}
        onCancel={() => setModalVisit3(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="标准柜体类型"
            name="standTypeDesc"
            rules={[{ required: true, message: '请选择标柜体类型!' }]}
          >
            <Select
              placeholder="请选择标准柜体类型"
              disabled //不可更改
              onChange={(value, label) => {}}
              options={optionsTypeDesc}
            />
          </Form.Item>
          <Form.Item
            label="标准柜体编号"
            name="standTypeCode"
            rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="标准柜体名称"
            name="standTypeName"
            rules={[{ required: true, message: '请输入标准柜体名称!' }]}
          >
            <Input disabled />
          </Form.Item>

          <Row justify={'space-between'}>
            <Col span={14}>
              <Form.Item
                label="文件类别"
                name="category"
                rules={[{ required: true, message: '请选择文件类别!' }]}
              >
                <Select
                  placeholder="请选择文件类别"
                  defaultValue=""
                  onChange={() => {}}
                  options={optionsstandfile}
                />
              </Form.Item>
            </Col>
            <Col>
              <Form.Item>
                {/* <Button
                  key="bombutton"
                  icon={<DownloadOutlined />}
                  onClick={() => {
                    bom_downloadFile({ id: '8a7f81828967ec7e01896cde08d50001' }).then((res) => {
                      const aLink = document.createElement('a');
                      document.body.appendChild(aLink);
                      aLink.style.display = 'none';
                      aLink.href = window.URL.createObjectURL(res);
                      console.log(res);
                      aLink.setAttribute('download', `BOM导入模板_20230719.xls`);
                      aLink.click();
                      document.body.removeChild(aLink);
                    });
                  }}
                  type="primary"
                >
                  下载BOM模板
                </Button> */}
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            <Upload
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={handleBeforeUpload}
              multiple={true}
            >
              <Button icon={<UploadOutlined />} className="standProduct_UploadStyle">
                上传文件
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <TextArea autoSize={{ minRows: 2, maxRows: 4 }} />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="right"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="标准柜体类型"
            name="standTypeDesc"
            rules={[{ required: true, message: '请选择标准柜体类型 !' }]}
          >
            <Select
              placeholder="请选择标准柜体类型"
              disabled={createOrUpdate} //不可更改
              onChange={(value, label) => {}}
              options={optionsTypeDesc}
            />
          </Form.Item>
          <Form.Item
            label="标准柜体编号"
            name="standTypeCode"
            rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
            hidden={!createOrUpdate}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="标准柜体名称"
            name="standTypeName"
            rules={[
              {
                required: true,
                validator: (rule, value, callback) => {
                  valueChangeValidCheck(value, callback);
                },
              },
            ]}
          >
            <Input maxLength={20} showCount />
          </Form.Item>
          <Form.Item
            label="工艺路径"
            name="bopCode"
            rules={[{ required: true, message: '请选择工艺路径!' }]}
          >
            <Select
              disabled={createOrUpdate}
              placeholder="请选择工艺路径"
              // disabled={createOrUpdate}//不可更改
              onChange={(value) => {}}
              options={optionsbopCode}
            />
          </Form.Item>
          <Form.Item
            label="计划设计工时"
            name="standDesignWorkHour"
            rules={[{ required: true, message: '请输入计划设计工时!' }]}
          >
            <Input
              addonAfter="h"
              onChange={(e) => handlestandDesignWorkHourChange(e.target.value)}
            />
          </Form.Item>
          {/* <Form.Item
            label="计划生产工时"
            name="standManufactWorkHour"
            rules={[{ required: true, message: '请输入计划生产工时!' }]}
          >
            <Input
              addonAfter="h"
              onChange={(e) => handlestandManufactWorkHourChange(e.target.value)}
            />
          </Form.Item> */}
          <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item>
          <Form.Item label="物料id" name="materialInfoId" hidden={true}>
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="物料编号"
            name="materialCode"
            rules={[{ required: true, message: '请选择物料编号 !' }]}
          >
            <Select
              showSearch
              placeholder="请选择物料编号"
              filterOption={filterOption}
              options={optionsMaterialCode}
              onChange={(value) => {
                let data = materialCodeToName.find((item: any) => item.materialCode === value);
                form.setFieldsValue({
                  materialName: data?.materialName,
                  materialInfoId: data?.materialInfoId,
                });
              }}
            />
          </Form.Item>
          <Form.Item label="物料名称" name="materialName">
            <Input disabled />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        open={open}
        title="柜体详情"
        width={1300}
        // onOk={handleOk}
        onCancel={handleCancel}
        destroyOnClose
        footer={
          [
            // <Button key="back" onClick={() => handleCancel()}>
            //   关闭
            // </Button>,
          ]
        }
      >
        <Tabs
          tabPosition="top"
          defaultActiveKey={activeKey}
          onChange={changeTabs}
          destroyInactiveTabPane={true} //隐藏tabs页时自动销毁DOM，再切换时生成DOM，重新获取最新数据
          items={tabList.map((item, i) => {
            const id = String(i + 1);
            return {
              label: item.label,
              key: id,
              children: <div>{item.content}</div>,
            };
          })}
        />
      </Modal>
      {/* 标准柜体审核弹窗页面 未审核 -> 已审核 */}
      <Modal
        title={'标准柜体审核'}
        visible={modalVisit4}
        onOk={handleSubmit2}
        confirmLoading={confirmLoading4}
        onCancel={() => setModalVisit4(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form1}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="standTypeId" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="审核结果"
            name="state"
            rules={[{ required: true, message: '请选择审核结果!' }]}
          >
            <Select
              defaultValue="选择审核结果"
              options={[
                { value: '2', label: '通过' },
                { value: '0', label: '驳回' },
              ]}
            />
          </Form.Item>
          <Form.Item label="审核描述" name="approveText">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
      {/* 工时上传 */}
      <Modal
        title="上传工时周期"
        visible={modalVisit5}
        onOk={workhour_upload}
        confirmLoading={confirmLoading5}
        onCancel={() => setModalVisit5(false)}
        destroyOnClose
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传工时周期文件!' }]}
          >
            <Upload
              accept="application"
              //listType="picture-card"
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default StandProduct;
